function loadMenu(obj){
	ajax({
		url:"/rss_list",
		method:"get",
		callback:Callback
	});
	function Callback(data){
		var data = json2Obj(data);
		var len = data.length;
		var menudata = [];
		var temp = '<a href="{url}" lang="{id}">{name}</a>';
		for (var n=0;n<len;n++){
			menudata.push({name:data[n].name,url:data[n].url,id:data[n].id})
		}
		obj.innerHTML = substitute(temp,menudata);
		transRss(obj);
	}
}
function openMusciPlayer(obj){
	if (window.navigator.userAgent.indexOf("Chrome") > -1){
		window.open ('static/mplayer.html','newwindow','height=350,width=400,top=0,left=0,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no')
	}else{
		alert("对不起，请使用chrome浏览器！")
	}
}
function RssManage(obj){
	ajax({
		url:"/rss_list",
		method:"get",
		callback:Callback
	});
	function Callback(data){
		var data = json2Obj(data);
		var len = data.length;
		var menudata = [];
		var tempTitle = '<h2>RSS管理</h2><a class="MsPoploadClose" href="javascript:void(0)" class="close" onclick="RssManageQuit()">×</a>'
		var tempH = '<div class="rsslist"><table>';
		var tempF = '</div></table>';
		var tempB = '<tr><td>{name}</td><td>{url}</td><td class="rsslist_op"><span onclick="RssEdit(this,{id})">编辑</span><span onclick="RssDel(this,{id})">删除</span></td></tr>';
		for (var n=0;n<len;n++){
			menudata.push({name:data[n].name,url:data[n].url,id:data[n].id})
		}
		var HTML = [tempTitle,tempH,substitute(tempB,menudata),tempF].join("");
		maskPop();
		MsPopload(HTML);
	}
}
function maskPop(){
	var h = Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight) + 'px';
	var w = document.documentElement.scrollWidth + 'px';
	pop_Box = document.createElement("div");
	pop_Box.id = "popBox";
	pop_Box.className = "dialog-mask";
	pop_Box.style.zIndex = "10";
	pop_Box.style.height = h;
	pop_Box.style.width = w;
	document.getElementsByTagName("body")[0].appendChild(pop_Box);
}
function RssManageQuit(){
	MsPoploadClose();
	window.location.href = "/";
	location.reload();
}
function RssEdit(obj,id){
	objP = obj.parentNode.parentNode;
	var tds = objP.getElementsByTagName("td");
	objP.innerHTML = ['<td><input type="text" value="',tds[0].innerHTML,'" style="width:90px" /></td><td><input type="text" value="',tds[1].innerHTML,'" style="width:300px;" /></td>','<td class="rsslist_op"><span onclick="RssSave(this,',id,')">保存</span><span onclick="RssDel(this,',id,')">删除</span></td>'].join("")	;
}
function RssSave(obj,id){
	objP = obj.parentNode.parentNode;
	var inputs = objP.getElementsByTagName("input");
	var name = inputs[0].value;
	var url = inputs[1].value;
	if ((name == "") ||(url == "")){
		alert("数据不允许为空，请输入");
		return false;
	}
	var data = ['action=edit&id=',id,'&name=',name,'&url=',url].join("");
	ajax({
		url:"/rss_item",
		method:"post",
		data:data,
		callback:Callback
	});
	function Callback(data){
		if (data == 1){
			objP = obj.parentNode.parentNode;
			objP.innerHTML = ['<td>',name,'</td><td>',url,'</td><td class="rsslist_op"><span onclick="RssEdit(this,',id,')">编辑</span><span onclick="RssDel(this,',id,')">删除</span></td>'].join("");
		}
	}
}
function RssDel(obj,id){
	ajax({
		url:"/rss_item",
		method:"post",
		data:'action=delete&id='+ id,
		callback:Callback
	});
	function Callback(data){
		if (data == 1){
			objP = obj.parentNode.parentNode;
			objP.parentNode.removeChild(objP);
		}
	}
}
function RssAddNew(obj){
	var name = $("#RssAddNewName").attr("value");
	var url = $("#RssAddNewUrl").attr("value");
	if (name.length == 0) {alert("请输入名称");return false}			
	if (url.substring(0,7) !== "http://"){alert("请输入合法有效的地址");return false;}
	urlAdd = [url,'&action=add&name=',name].join("");
	ajax({
		url:"/rss_item",
		method:"post",
		data:{url:urlAdd},
		callback:Callback
	});
	function Callback(data){
		if (data !== '0'){
			window.location.href = 'http://localhost:8080/#!rss='+url;
			location.reload();
		}
	}
	MsPoploadClose();
}
function MyRssAdd(obj){
	objP = obj.parentNode.parentNode;
	var tds = objP.getElementsByTagName("td");
	var name = tds[0].innerHTML;
	var url = tds[1].innerHTML;
	data = ['action=add&name=',name,'&url=',url].join("");
	ajax({
		url:"/rss_item",
		method:"post",
		data:data,
		callback:Callback
	});
	function Callback(data){
		if (data !== '0'){
			objP.className += " selected";
			obj.innerHTML = "订阅成功"
		}
	}
}
function addNewRss(obj){
	var popStr = [
				'<span>请输入Rss地址</span><a class="MsPoploadClose" href="javascript:void(0)" class="close" onclick="MsPoploadClose()">×</a>',
				'<input type="text" id="RssAddNewName" class="text RssAddNewName" />',
				'<input type="text" id="RssAddNewUrl" class="text RssAddNewUrl" />',
				'<input type="submit" class="submit" value="添加" onclick="RssAddNew(this)" />'].join("");
	if (document.getElementById("PopOutDiv")) {
		var obj = document.getElementById("PopOutDiv");
		obj.parentNode.removeChild(obj);
	}
	div = document.createElement("div");
	document.getElementById("wrap").appendChild(div);
	div.id = "PopOutDiv";
	div.className = "PopOutDiv addNewRss";
	div.innerHTML = popStr;
	var obj = document.getElementById("PopOutDiv");	
	obj.style.top = '50px';
	obj.style.right = '10px';
}
function MsPoploadClose(){
	var obj = document.getElementById("PopOutDiv");
	if (!obj){return false;}        
	//ie6 bugfix
	setTimeout(function(){
		obj.parentNode.removeChild(obj);
	},0);
}
function transRss(obj){
	var as = obj.getElementsByTagName("a");
	var len = as.length;
	if(len<1){
		var rssReady = ['<div class="rsslist rssReady"><table class="rssForAdd">',
						'<tr>',
						'  <td>都市客·良品杂志</td>',
						'  <td>http://feed.feedsky.com/metroer</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>前端集锦</td>',
						'  <td>http://cid-82b93402dd7f509a.users.api.live.net/Users(-9027126791176761190)/Main?$format=rss20</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>译言-生活点滴</td>',
						'  <td>http://feed.feedsky.com/yeeyan-life</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>每日鲜果精选</td>',
						'  <td>http://www.xianguo.com/service/dailyshare</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>今日焦点</td>',
						'  <td>http://www.ftchinese.com/rss/news</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>岁月如歌</td>',
						'  <td>http://lifesinger.org/blog/?feed=rss2</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>彬Go</td>',
						'  <td>http://feed.feedsky.com/bingo929</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>样式之美</td>',
						'  <td>http://feeds.feedburner.com/aoao</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>以用户为中心的设计</td>',
						'  <td>http://feed.feedsky.com/whitecrow_read</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>十大热门文章</td>',
						'  <td>http://www.ftchinese.com/rss/hotstoryby7day</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>每日英语</td>',
						'  <td>http://www.ftchinese.com/rss/diglossia</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>第一时间解读</td>',
						'  <td>http://www.ftchinese.com/rss/column/007000005</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>马丁 沃尔夫</td>',
						'  <td>http://www.ftchinese.com/rss/column/007000012</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>读者有话说</td>',
						'  <td>http://www.ftchinese.com/rss/letter</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>生活时尚</td>',
						'  <td>http://www.ftchinese.com/rss/lifestyle</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'<tr>',
						'  <td>远观中国</td>',
						'  <td>http://www.ftchinese.com/rss/column/007000004</td>',
						'  <td><span onClick="MyRssAdd(this)">添加订阅</span></td>',
						'</tr>',
						'</table></div>'].join("");
		$("#feedTitle").html("您还没有添加RSS,我们为您推荐一下RSS");
		$("#feedshow").html(rssReady);
		return false;
	}
	var objt = document.getElementById("feedTitle");
	var rssPath;
	if(getPara(location.href,'rss')){
		rssPath = getPara(location.href,'rss');
	}else{
		rssPath = as[0].href;
	}
	writeHash("rss",rssPath);
	insertJS(rssPath);
	for(j=0;j<len;j++) {
		if(as[j].href == rssPath){
			objt.innerHTML = as[j].innerHTML;
			objt.lang = as[j].lang;
			as[j].className += " current";
		}
		as[j].onclick = function(){
			div.innerHTML = '<p class="loading"></p>';
			for(var n=0;n<len;n++){as[n].className = as[n].className.replace("current","");}
			this.className += " current";
			insertJS(this.href);
			writeHash("rss",this.href);
			objt.innerHTML = this.innerHTML;
			objt.lang = this.lang;
			return false;
		}
	}
	function insertJS(url){
        ajax({
            url:"/rss_item",
            method:"get",
            data:{url:url},
            callback:XmlCallBack
        });        
	}
}
function XmlCallBack(xml){
	var xmlDoc = XmlLoad(xml);
	var cNodes = xmlDoc.getElementsByTagName("item"); 
	var len = cNodes.length;
	var msg = "<ul>";
	for(j=0;j<len;j++) { 
		var href = cNodes[j].getElementsByTagName("link")[0].childNodes[0].nodeValue;
		var title = cNodes[j].getElementsByTagName("title")[0].childNodes[0].nodeValue;
		var time = cNodes[j].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;
		var desc = cNodes[j].getElementsByTagName("description")[0].childNodes[0].nodeValue;
		msg = [msg,
			'<li>',
			'<h3><a href="',href,'" class="title">',title,'</a><small>',time,'</small></h3>',
			'<div class="feedshow_content">',desc,',<a href="',href,'">【全文】</a></div>',
			'</li>'].join("");
	}
	msg = [msg,'</ul>'].join("");
	
	div.innerHTML = msg;
	var lis = div.getElementsByTagName("h3");
	var len = lis.length;
	for(var i=0;i<len;i++){
		lis[i].num = i;
		lis[i].onclick = function(){
			for(var n=0;n<len;n++){lis[n].parentNode.className = lis[n].parentNode.className.replace("open","")}
			this.parentNode.className += " open";
			reading.now = this.num;
			scrollOpen(reading.now);
			return false;
		}
	}
	 keyboard();
}
function keyboard(){
	var obj;
	if (navigator.userAgent.indexOf("MSIE")>0){
		obj = document.getElementsByTagName("body")[0];
	}else{
		obj = window;
	}	
	obj.onkeyup = function(event){
		var event = event || window.event;
		var keyCode = event.which || event.keyCode;
		if (keyCode == 32) {next();}
		if (keyCode == 40) {next();}
		if (keyCode == 74) {next();}

		
		if (keyCode == 38) {prew();}
		if (keyCode == 75) {prew();}
	}
}

function prew(){
	var lis = div.getElementsByTagName("h3");
	var len = lis.length;
	var index = reading.now;
	if (index>0){
		for(var n=0;n<len;n++){lis[n].parentNode.className = lis[n].parentNode.className.replace("open","")}
		lis[index-2].parentNode.className += " open";
		scrollOpen(index-2);
		reading.now -= 2;
	}
}
function next(){
	var lis = div.getElementsByTagName("h3");
	var len = lis.length;
	var index = reading.now;
	if (index<len){
		for(var n=0;n<len;n++){lis[n].parentNode.className = lis[n].parentNode.className.replace("open","")}
		lis[index].parentNode.className += " open";
		scrollOpen(index);
		reading.now += 1;
	}
}
function scrollOpen(n){
	$("#feedshow").scrollTop(28*n)
}
function emailRss(){
	if($("#feedshow li.open").length == 0){alert("对不起，您还未打开文章");return false;}
	var title = $("#feedshow li.open h3").html();
	var text =  $("#feedshow li.open .feedshow_content").html();
	$("#rec_text").html("<h3>" + title + "</h3>" + text)
	$("#emailPanel").show()
}
function emailRssSend(){
	ajax({
		url:"/mail",
		method:"post",
		data:{email:document.getElementById("rec_email").value,subject:document.getElementById("rec_title").value,body:document.getElementById("rec_text").innerHTML},
		callback:function(){
			alert("发送成功！");
		}
	});
	$("#emailPanel").hide();	
}
function emailRssCancel(){
	$("#emailPanel").hide();
}
function HomeSameHeight(minH){
	objL = document.getElementById("menu");
	objR = document.getElementById("feedshow");

	if (objL && objR){		
		var hb = document.documentElement.clientHeight - 70 + "px";
		var hs = document.documentElement.clientHeight - 130 + "px"
		objL.style.height = hb;
		objR.style.height = hs;
	}
}
function XmlLoad(XmlText) {
	var xmlDoc;
	try{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML(XmlText);    
	}catch(e){
		try{
			xmlDoc=document.implementation.createDocument("","",null);
			parser=new DOMParser();
			var xmlDoc = parser.parseFromString(XmlText,"text/xml")

		}catch(e){}
	}	
	return xmlDoc;	
}
function ajax(option){
	var xhr = (window.ActiveXObject)?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
    dataEncode();
	try{
        if(option.async !== false){
            option.async = true;
        }
		xhr.open(option.method||"POST",option.url,option.async);
		xhr.setRequestHeader("Content-Type",option.contentType||"application/x-www-form-urlencoded");
		xhr.onreadystatechange = handleStateChange;        
		xhr.send(option.data);
	}catch (ex) {
		return "";
	}
	function handleStateChange(){
		if (xhr!=null&&xhr.readyState==4){
			if(option.callback){
				option.callback(xhr.responseText);
			}
		} 
	}
    function dataEncode(){
      var qs=[];
      if(option.data){
        if(typeof(option.data)=="string"){
          qs.push(option.data);
        }else{
          for(var x in option.data){                                    
            qs.push(x);
            qs.push("=");
            qs.push(option.data[x]);
            qs.push("&");
          }
          qs.pop();
        }
      }
      if(option.method && option.method.toLowerCase()=="get"){
        qs.unshift(option.url.indexOf("?")==-1?"?":"&");
        option.url=option.url + qs.join("");
        option.data = "";
      }else{
        option.data = qs.join("");
      }    
    }
}
function insertAfter(newElement,targetElement) {   
	var parent = targetElement.parentNode;   
	if (parent.lastChild == targetElement) {   
		parent.appendChild(newElement);   
	} else {   
		parent.insertBefore(newElement,targetElement.nextSibling);   
	}
}
function substitute(template, data, regexp){
  if(!(Object.prototype.toString.call(data) === "[object Array]")){
	data = [data]
  }
  var ret = [];
  for(var i=0,j=data.length;i<j;i++){
	ret.push(replaceAction(data[i]));
  }
  return ret.join("");
  
  function replaceAction(object){
	return template.replace(regexp || (/\\?\{([^}]+)\}/g), function(match, name){
	 if (match.charAt(0) == '\\') return match.slice(1);
	 return (object[name] != undefined) ? object[name] : '';
	});
  }
}
function getPara(str,para){
	var result,ParaStr;
	if(str.indexOf("#!")>-1){
		ParaStr = str.split("#!")[1];
	}else if(str.indexOf("?")>-1){
		ParaStr = str.split("?")[1];
	}else{
		return false;
	}
	var ParaArr = ParaStr.split("&");
	var len = ParaArr.length;
	for (var n=0;n<len;n++){
		if (ParaArr[n].indexOf(para)>-1){
			result = ParaArr[n].replace(para + "=","") 
		}
	}
	return result;
}
function writeHash(prop,value){
	var address = location.hash;
	if (address.indexOf("#!")>-1){
		var v = getPara(address,prop);
		if(v){
			location.hash = address.replace(prop+"="+v,prop+"="+value);
		}else{
			var hash = '&' + prop +'=' + value;
			location.hash += hash;
		}
	}else{
		location.hash = "#!" + prop + '=' +value;	
	}
}
function json2Obj(astr){
	var ljson;
	if(typeof astr == "object"){
		return astr;
	}
	astr = (astr != null) ? astr.split("\n").join("").split("\r").join("") : "";
	if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(astr.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) {
		if (astr != "") {
			ljson = eval('(' + astr + ')');
			return ljson;
		}
	}
	return {};
}
function MsPopload(str){
	if (document.getElementById("PopOutDiv")) {
		var obj = document.getElementById("PopOutDiv");
		obj.parentNode.removeChild(obj);
	}
	div = document.createElement("div");
	document.getElementsByTagName("body")[0].appendChild(div);
	div.id = "PopOutDiv";
	div.className = "PopOutDiv";
	div.innerHTML = str;
	var obj = document.getElementById("PopOutDiv");
	obj.style.cssText = "display:block;position:absolute;z-index:225;width:500px;"	
	obj.style.top = (document.documentElement.scrollTop+document.body.scrollTop+document.documentElement.clientHeight/2-obj.offsetHeight/2)+ 'px';
	obj.style.left = (document.documentElement.clientWidth/2-obj.offsetWidth/2) + 'px';
}
function MS_loadJsonP(asUrl, afCallback){
     if (!asUrl) {
        return false;
     }
     var lsUrl = asUrl;
     if (lsUrl.indexOf("callback=") == -1) {
        var lsGUID="_autoCallBack"+Math.floor(Math.random()*16000).toString(16);
        lsUrl = lsUrl + (lsUrl.indexOf("?") != -1 ? "&" : "?") + "callback=" + lsGUID;
     }
     window[lsGUID] = afCallback;
     
     var leTag = document.createElement('script');
     leTag.setAttribute('type', 'text/javascript');
     leTag.setAttribute('src', lsUrl);
     document.getElementsByTagName('head')[0].appendChild(leTag);                                  
} 